﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Giaiphongmatbang.BLL;
using Giaiphongmatbang.UserControl;
using Giaiphongmatbang.DataModel;

namespace Giaiphongmatbang
{
    public partial class duan : System.Web.UI.Page
    {
        QLGPMBEntities db = new QLGPMBEntities();
        DataAccess.GPMBDataContext datacontext = new DataAccess.GPMBDataContext();
        User user;        
        protected void Page_Load(object sender, EventArgs e)
        {
            ucPaging1.PageChange += new ucPaging.PagingHandler(BindDataProject);
            ucPaging2.PageChange += new ucPaging.PagingHandler(BindDataHouseHold);
            user = (User)Session["User"] ?? db.Users.FirstOrDefault(p=>p.UserName.Equals("guest"));
            Title = ":: Phần mền hỗ trợ dự toán chi phí GPMB - UBND Huyện Hưng Nguyên ::";
            if (!IsPostBack)
            {
                ucPaging1.CurrentPage = 1;
                ucPaging1.PageSize = 50;
                ucPaging1.PageDisplay = 6;
                ucPaging2.CurrentPage = 1;
                ucPaging2.PageSize = 50;
                ucPaging2.PageDisplay = 6;
                drdChoose.Visible = (Session["User"]!=null);
                btnDetailExport.Visible = (Session["User"] != null);
                btnExport.Visible = (Session["User"] != null);
                btnExportDetail.Visible = (Session["User"] != null);
                try
                {
                    option = int.Parse(Request.QueryString["option"]);                    
                }
                catch
                {
                    option = 0;

                }
                seach = false;                                            
                childNav1.BindData(1);
                if (Session["ProjectID"] != null)
                {
                    ProjectID = (int)Session["ProjectID"];
                    ShowPanel2();
                }
                BindDataProject();  
            }
        }

        #region variable
        int ProjectID
        {
            set { ViewState["ProjectID"] = value; }
            get { return (int)ViewState["ProjectID"]; }
        }

        string CMND
        {
            set { ViewState["CMND"] = value; }
            get { return (string)ViewState["CMND"]; }
        }
        int HouseHoldID
        {
            set { ViewState["HouseHoldID"] = value; }
            get { return (int)ViewState["HouseHoldID"]; }
        }
        int option
        {
            get { return (int)ViewState["option"]; }
            set { ViewState["option"] = value; }
        }
        bool seach
        {
            get { return (bool)ViewState["seach"]; }
            set { ViewState["seach"] = value; }
        }
        double? TotalCompensate
        {
            get { return ViewState["TotalCompensate"] == null ? 0 : (double?)ViewState["TotalCompensate"]; }
            set { ViewState["TotalCompensate"] = value; }
        }
        double? TotalSupport
        {
            get { return ViewState["TotalSupport"] == null ? 0 : (double?)ViewState["TotalSupport"]; }
            set { ViewState["TotalSupport"] = value; }
        }
        #endregion
        #region GridView Project
        protected void BindDataProject()
        {
            int totalRow = 0;
            ProjectsRepository repository = new ProjectsRepository();
            IEnumerable<Giaiphongmatbang.DataModel.Project> datasouce;
            if (seach)
            {
                int? totalRecord = 0;
                string ProjectName = txtProjectName.Text.Trim();
                DateTime? startDate;
                try { startDate = Convert.ToDateTime(txtFrom.Text); }
                catch { startDate = null; }
                DateTime? endDate;
                try { endDate = Convert.ToDateTime(txtTo.Text); }
                catch { endDate = null; }
                var data = new Giaiphongmatbang.DataAccess.GPMBDataContext().uspProjectSearch(ProjectName, startDate, endDate, ucPaging1.CurrentPage, ucPaging1.PageSize, ref totalRecord);              
                totalRow = totalRecord.Value;
                grvProject.DataSource  = data;
            }
            else
            {
                switch (option)
                {
                    case 0:
                        datasouce = repository.GetIsPublic(ucPaging1.PageSize, ucPaging1.CurrentPage, ref totalRow);
                        break;
                    case 1:
                        datasouce = repository.GetAll(ucPaging1.PageSize, ucPaging1.CurrentPage, ref totalRow);
                        break;
                    case 2:
                        datasouce = repository.GetProjectCompleted(ucPaging1.PageSize, ucPaging1.CurrentPage, ref totalRow);
                        break;
                    case 3:
                        datasouce = repository.GetProjectnotIsCompleted(ucPaging1.PageSize, ucPaging1.CurrentPage, ref totalRow);
                        break;
                    case 4:
                        datasouce = repository.GetIsPublic(ucPaging1.PageSize, ucPaging1.CurrentPage, ref totalRow);
                        break;
                    case 5:
                        datasouce = repository.GetnotIsPublic(ucPaging1.PageSize, ucPaging1.CurrentPage, ref totalRow);
                        break;
                    default:
                        datasouce = repository.GetIsPublic(ucPaging1.PageSize, ucPaging1.CurrentPage, ref totalRow);
                        break;
                }
                grvProject.DataSource = datasouce;                
            }
            ucPaging1.TotalRecord = totalRow;
            ucPaging1.Visible = (ucPaging1.TotalPage > 1);
            grvProject.DataBind();
            if(grvProject.Rows.Count == 0)          
                ltrMessage.Text = "<p>Không có dự án nào để hiện thị</p>";        
        }
        protected void grvProject_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (Session["User"] == null)
            {
                int columnCount = grvProject.Columns.Count;
                grvProject.Columns[columnCount - 1].Visible = false;
                return;
            }

        }
        protected void grvProject_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            User user = (User)Session["User"];
            UserRolesRepository repository = new UserRolesRepository();
            string commandName = e.CommandName;
            ProjectID = int.Parse(e.CommandArgument.ToString());
            if (commandName.Equals("btnEdit"))
            {
                if(!repository.CheckRoles(user,(int)Utility.Enum.Roles.UpdateProject))
                {
                    ScriptManager.RegisterStartupScript(this,this.GetType(),"","alert('Bạn không đủ quyền hạn!');",true);
                    return;
                }                
                Response.Redirect("editDuan.aspx?ID=" + ProjectID);
            }

            else if(commandName.Equals("btnDelete"))
            {
                if (!repository.CheckRoles(user, (int)Utility.Enum.Roles.DeleteProject))
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Bạn không đủ quyền hạn!');", true);
                    return;
                }
                db.DeleteObject(db.Projects.FirstOrDefault(p => p.ProjectID == ProjectID));
                db.SaveChanges();
                BindDataProject();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Xóa thành công!');", true);
            }
            else if (commandName.Equals("btnView"))
            {
                btnInsert.Visible = (Session["User"] != null);
                ShowPanel2();
            }
        }
        #endregion
        #region GridView HouseHold
        protected void BindDataHouseHold()
        {
            if (!seach)
            {
                int? totalRow = 0;
                grvHouseHold.DataSource = new DataAccess.GPMBDataContext().uspHouseHoldSearch(ProjectID, null, null, ucPaging2.CurrentPage, ucPaging2.PageSize, ref totalRow);
                ucPaging2.TotalRecord = totalRow.Value;
            }
            else
            {
                int? totalRow = 0;
                grvHouseHold.DataSource = new DataAccess.GPMBDataContext().uspHouseHoldSearch(ProjectID, "", txtHouseHold.Text.Trim(), ucPaging2.CurrentPage, ucPaging2.PageSize, ref totalRow);
                ucPaging2.TotalRecord = totalRow.Value;
            }            
            ucPaging2.Visible = (ucPaging2.TotalPage > 1);
            grvHouseHold.DataBind();
            if (grvHouseHold.Rows.Count == 0)
                Literal1.Text = "Không tìm thấy chủ hộ!";
        }
        protected void grvHouseHold_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (Session["User"] == null)
            {
                int columnCount = grvHouseHold.Columns.Count;
                grvHouseHold.Columns[columnCount - 1].Visible = false;
                return;
            }
        }

        UserRolesRepository repository = new UserRolesRepository();
        protected void grvHouseHold_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("btnEdit"))
            {
                int HouseHoldID = int.Parse(e.CommandArgument.ToString());
                if (repository.CheckRoles(user, (int)Utility.Enum.Roles.UpdateProject))
                {
                    Response.Redirect("/editObject.aspx?hID=" + HouseHoldID + "&pID=" + ProjectID);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Bạn không đủ quyền thực hiện chức năng này!');", true);
                    return;
                }
            }
            else if (e.CommandName.Equals("btnDelete"))
            {
                int HouseHoldID = int.Parse(e.CommandArgument.ToString());
                if (!repository.CheckRoles(user, (int)Utility.Enum.Roles.UpdateProject))
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Bạn không đủ quyền thực hiện chức năng này!');", true);
                    return;
                }
                new HouseHoldRepository().DeleteFromProject(ProjectID, HouseHoldID);
                BindDataHouseHold();
            }
        }
        #endregion        
        #region Repeater Land
        protected void BindDataLand()
        {
            List<DataAccess.uspGetAllInventLandResult> datasource = datacontext.uspGetAllInventLand(ProjectID, CMND).ToList();
            rptLand.DataSource = datasource;
            rptLand.DataBind();
            TotalCompensate += datasource.Sum(p => p.toAmounts);
        }
        #endregion
        #region Repeater HouseType
        protected void BindDataHouse()
        {
            int? TotalRow = 0;
            var datasource = datacontext.uspGetInventHouse(ProjectID, ref TotalRow).Where(p => p.CMND.Equals(CMND)).ToArray();
            rptHouse.DataSource = datasource;
            rptHouse.DataBind();
            TotalCompensate += datasource.Sum(p => p.toAmount);
        }
        #endregion
        #region Repeater Building
        protected void BindDataBuilding()
        {
            int? TotalRow = 0;
            var datasource = datacontext.uspGetInventBuilding(ProjectID, ref TotalRow).Where(p => p.CMND.Equals(CMND)).ToArray();
            rptBuilding.DataSource = datasource;
            rptBuilding.DataBind();
            TotalCompensate += datasource.Sum(p => p.toAmount);
        }
        #endregion
        #region Repeater Graves
        protected void BindDataGraves()
        {
            int? TotalRow = 0;
            var datasource = datacontext.uspGetInventGrave(ProjectID, ref TotalRow).Where(p => p.CMND.Equals(CMND)).ToArray();
            rptGraves.DataSource = datasource;
            rptGraves.DataBind();
            TotalCompensate += datasource.Sum(p => p.toAmount);
        }
        #endregion
        #region Repeater Trees
        protected void BindDataTrees()
        {
            int? TotalRow = 0;
            var datasource = datacontext.uspGetInventTree(ProjectID, ref TotalRow).Where(p => p.CMND.Equals(CMND)).ToArray();
            rptTrees.DataSource = datasource;
            rptTrees.DataBind();
            TotalCompensate += datasource.Sum(p => p.toAmount);
        }
        #endregion
        #region Repeater SupportMove
        protected void BindDataSupportMove()
        {
            int? TotalRow = 0;
            var datasource = datacontext.uspEstimateSupportMove(ProjectID, ref TotalRow).Where(p => p.CMND.Equals(CMND)).ToArray();
            rptSupportMove.DataSource = datasource;
            rptSupportMove.DataBind();
            TotalSupport += (double?)datasource.Sum(p => p.toAmount);
        }
        #endregion
        #region Repeater Support Rent
        protected void BindDataSupportRent()
        {
            int? TotalRow = 0;
            var datasource = datacontext.uspEstimateSupportRent(ProjectID, ref TotalRow).Where(p => p.CMND.Equals(CMND)).ToArray();
            rptSupportRent.DataSource = datasource;
            rptSupportRent.DataBind();
            TotalSupport += (double?)datasource.Sum(p => p.toAmount);
        }
        #endregion
        #region Repeater SupportStalibize
        protected void BindDataSupportStabilize()
        {
            int? TotalRow = 0;
            var datasource = datacontext.uspEstimateSupportStabilize(ProjectID, ref TotalRow).Where(p => p.CMND.Equals(CMND)).ToArray();
            rptSupportStabilize.DataSource = datasource;
            rptSupportStabilize.DataBind();
            TotalSupport += (double?)datasource.Sum(p => p.toAmount);
        }
        #endregion
        #region Repeater SupportJob
        protected void BindDataSupportJob()
        {
            int? TotalRow = 0;
            var datasource = datacontext.uspEstimateSupportJob(ProjectID, ref TotalRow).Where(p => p.CMND.Equals(CMND)).ToArray();
            rptSupportJob.DataSource = datasource;
            rptSupportJob.DataBind();
            TotalSupport += (double?)datasource.Sum(p => p.toAmount);
        }
        #endregion
        #region Repeater SupportOther
        protected void BindDataSupportOther()
        {
            var datasource = new SupportOtherRepository().GetByProjectIDAndCMND(ProjectID, CMND).ToArray();
            rptSupportOther.DataSource = datasource;
            rptSupportOther.DataBind();
            TotalSupport += (double?)datasource.Sum(p =>p.UnitPrice);
        }
        #endregion
        #region Command
        public void ShowPanel2()
        {
            seach = false;
            pnl1.Visible = false;
            pnl2.Visible = true;
            Project currentProject = new ProjectsRepository().GetByID(ProjectID);
            ltrProjectName.Text = currentProject.ProjectName;
            ltrProjectInvestor.Text = currentProject.Investor;
            BindDataHouseHold();
            btnEdit.Visible = repository.CheckRoles(user, (int)Utility.Enum.Roles.UpdateProject);
            btnDelete.Visible = repository.CheckRoles(user, (int)Utility.Enum.Roles.UpdateProject);
        }
        protected void lbtView_Click(object sender, EventArgs e)
        {
            LinkButton lbt = (LinkButton)sender;
            CMND = (string)lbt.CommandArgument;
            pnl1.Visible = false;
            pnl2.Visible = false;
            pnl3.Visible = true;
            HouseHold h = new HouseHoldRepository().GetByCMND(CMND);
            ltrFullName.Text = h.FullName;
            ltrAddress.Text = h.Address;
            ltrGender.Text = (h.Gender == true) ? "Nam" : "Nữ";
            ltrMemberCount.Text = h.MemberCount.ToString();
            TotalSupport = 0;
            TotalCompensate = 0;
            BindDataLand();
            BindDataBuilding();
            BindDataHouse();
            BindDataTrees();
            BindDataGraves();
            BindDataSupportMove();
            BindDataSupportRent();
            BindDataSupportStabilize();
            BindDataSupportJob();
            BindDataSupportOther();
            if (TotalCompensate.HasValue && TotalCompensate.Value > 0)
            {
                ltrTotalCompensate.Text = "<tr><td colspan='3'><b>Tổng cộng</b></td><td><b>" + TotalCompensate.Value.ToString("###,###") + "&nbsp;(đồng)</b></td></tr>";
            }
            if (TotalSupport.HasValue && TotalSupport.Value > 0)
            {
                ltrTotalSupport.Text = "<tr><td><b>Tổng cộng</b></td><td><b>" + TotalSupport.Value.ToString("###,###") + "&nbsp;(đồng)</b></td></tr>";
            }
        }
        protected void btnReturn1_Click(object sender, EventArgs e)
        {
            Session["ProjectID"] = null;
            if (!seach)
            {
                pnl1.Visible = true;
                pnl2.Visible = false;
            }
            else
            {
                seach = false;
                BindDataHouseHold();
            }
        }
        protected void btnReturn2_Click(object sender, EventArgs e)
        {
            seach = false;
            pnl3.Visible = false;
            pnl2.Visible = true;
        }
        protected void btnInsert_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("/addObject.aspx?id=" + ProjectID);
        }
        protected void btnShow_Click(object sender, EventArgs e)
        {
            seach = true;
            BindDataProject();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            seach = true;
            BindDataHouseHold();
        }
        protected void drdChoose_SelectedIndexChanged(object sender, EventArgs e)
        {
            option = int.Parse(drdChoose.SelectedValue);
            seach = false;
            BindDataProject();
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            HouseHoldID = db.HouseHolds.FirstOrDefault(p => p.CMND.Equals(CMND)).HouseHoldID;
            Response.Redirect("/editObject.aspx?hID=" + HouseHoldID + "&pID=" + ProjectID);
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            new HouseHoldRepository().DeleteFromProject(ProjectID, CMND);
            BindDataHouseHold();
            pnl3.Visible = false;
            pnl2.Visible = true;
        }

        protected void btnCostEstimate_Click(object sender, EventArgs e)
        {
            Response.Redirect("CostEstimate.aspx?pID=" + ProjectID);
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=baocao.doc");
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());
            Response.Output.Write(Utility.Utilities.MSWordHeader("a4", true) + new Exports().getEstimateByProjectID1(ProjectID) + Utility.Utilities.MSWordFooter());
            Response.Flush();
            Response.End();
        }
        protected void btnDetailExport_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            //excel
            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=Bao-Cao-Chi-Tiet.doc");
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());
            string re = Utility.Utilities.MSWordHeader() + new Exports().getPricePressure(ProjectID) + Utility.Utilities.MSWordFooter();
            Response.Write(re);
            Response.Flush();
            Response.End();
        }

        protected void btnExportDetail_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            //excel
            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=Bao-Cao-Chi-Tiet.doc");
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());
            string re = Utility.Utilities.MSWordHeader() + new Exports().getHouseDetail(ProjectID, CMND) + Utility.Utilities.MSWordFooter();
            Response.Write(re);
            Response.Flush();
            Response.End();
        }
        #endregion

        




        
    }
}